package com.leo.chapter08;

import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.Semaphore;

/**
 * 用Semaphore控制任务的提交速率
 * @author xuexiaolei
 * @version 2017年10月18日
 */
public class BoundedExector {
    private final Executor exec;
    private final Semaphore semaphore;

    public BoundedExector(Executor exec, Semaphore semaphore) {
        this.exec = exec;
        this.semaphore = semaphore;
    }

    public void submitTask(final Runnable r) throws InterruptedException {
        semaphore.acquire();
        try {
            exec.execute(new Runnable() {
                @Override public void run() {
                    try {
                        r.run();
                    } finally {
                        semaphore.release();
                    }
                }
            });
        } catch (RejectedExecutionException e){
            semaphore.release();
        }
    }
}
